package threadLearn.v2;

import java.util.ArrayList;
import java.util.List;

class ThreadA implements Runnable{

	Object lock;
	List<String> list;
	public ThreadA(Object lock,List<String> list) {
		this.lock = lock;
		this.list = list;
	}
	@Override
	public void run() {
		synchronized (lock) {
			for(int i = 0; i < 10; i++) {
				list.add(""+i);
				System.out.println("添加："+i);
				if(i == 5)
					lock.notifyAll();
					System.out.println("发出通知！");
			}
		}
	}
}

class ThreadB implements Runnable{

	Object lock;
	List<String> list;
	public ThreadB(Object lock,List<String> list) {
		this.lock = lock;
		this.list = list;
	}
	@Override
	public void run() {
		synchronized (lock) {
			if(list.size() != 5) {
				try {
					System.out.println("wait开始："+System.currentTimeMillis());
					lock.wait();
					System.out.println("wait结束："+System.currentTimeMillis());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
}

public class WaitNotifyTest {
	
	public static void main(String[] args) throws InterruptedException {
		Object lock = 1;
		List<String> list = new ArrayList<>();
		ThreadA a = new ThreadA(lock, list);
		ThreadB b = new ThreadB(lock, list);
		/**
		 * notify执行后并不会立即释放锁
		 * notify只通知一个线程
		 * notifyAll通知所有阻塞线程，优先级最高的最先执行，也有可能随机，取决于JVM
		 */
		new Thread(a).start();
		//Thread.sleep(1000);
		new Thread(b).start();
		
	}

}
